﻿using HSGD.Common;
using HSGD.Common.HttpContextUser;
using HSGD.IServices.HSGD_Logs;
using HSGD.IServices.HSGD_Staff;
using HSGD.Model.Common;
using HSGD.Model.Dtos.HSGD_Staff;
using HSGD.Model.Models.HSGD_Staff;
//using HSGD.Model.Validators;
using HSGD.Repository.UnitOfWorks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;

namespace HSGD.Api.Controllers {
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize(Permissions.Name)]
    public class PersonController : ControllerBase {
        private readonly IPersonServices _personServices;
        private readonly IEssayFormServices _essayFormServices;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IUser _user;
        public IHSGDLogsServices _logsServices { get; set; }
        //public IRefEmailNoticeServices _refEmailNoticeServices { get; set; }

        public PersonController(IPersonServices personservices,
            IEssayFormServices essayFormServices,
            IUnitOfWorkManage unitOfWorkManage, IUser user) {
            _essayFormServices = essayFormServices;
            _personServices = personservices;
            _unitOfWorkManage = unitOfWorkManage;
            _user = user;
        }

        [HttpGet]
        public async Task<MessageModel<PageModel<Person>>> Get(int page = 1, string key = "", int intPageSize = 50) {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key)) {
                key = "";
            }

            Expression<Func<Person, bool>> whereExpression = a => true;

            //return new MessageModel<PageModel<Person>>() {
            //    msg = "获取成功",
            //    success = true,
            //    response = await _personServices.QueryPage(whereExpression, page, intPageSize)
            //};

            var res = await _personServices.QueryPage(whereExpression, page, intPageSize);
            return MessageModel<PageModel<Person>>.Success(res);
        }

        [HttpGet("{id}")]
        public async Task<MessageModel<PersonDto>> Get(string id) {
            //return new MessageModel<PersonDto>() {
            //    msg = "获取成功",
            //    success = true,
            //    response = await _personServices.GetPersonByEinfoId(id)
            //};
            var res = await _personServices.GetPersonByEinfoId(id);
            return MessageModel<PersonDto>.Success(res);

        }
        private const string ADMIN = "admin";

        [HttpGet]
        [Route("api/perosn/add")]
        //[Authorize(Roles = ADMIN)]
        [Authorize("Permission")]
        public async Task<object> Get() {
            try {
                Console.WriteLine($"Begin Transaction");

                //using var uow = _unitOfWorkManage.CreateUnitOfWork();
                var roles = await _personServices.Query();
                var first = roles.FirstOrDefault(x => x.EInfo_id == "1871");
                Console.WriteLine($"1 first time : the count of role is :{roles.Count} ${first?.EInfo_id}");


                Console.WriteLine($"insert a data into the table role now.");
                await _logsServices.AddAsync(new Model.Models.HSGD_Logs.Logs() { age = 15, name = $"name1", gender = 'M', create_dt = DateTime.Now });
                //TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                await _personServices.AddPersonAsync(new Person() {
                    Person_System_ID = "003AB1E106444CV",
                    EInfo_id = "1000",
                    Person_Type = "1",
                    SSN = "644-22-7981",
                    Name_Last = "Karimi",
                    Name_First = "Olubode",
                    Date_Birth = DateTime.Parse("3/23/2010"),
                });


                var roles2 = await _personServices.First(x => x.Person_System_ID == "003AB1E106444CV");
                Console.WriteLine($"Update_Date :{roles2?.Update_Date}");


                //int ex = 0;
                //Console.WriteLine($"There's an exception!!");
                //Console.WriteLine($" ");
                //int throwEx = 1 / ex;

                //uow.Commit();
            }
            catch (Exception) {
                var roles3 = await _personServices.Query();
                Console.WriteLine($"3 third time : the count of role is :{roles3.Count}");
            }

            return "ok";
        }
        [HttpGet]
        [Route("api/perosn/add1")]
        [Authorize(Policy = "Policy_HSGDeMS")]
        public async Task<object> Get1() {
            try {
                Console.WriteLine($"Begin Transaction");

                //using var uow = _unitOfWorkManage.CreateUnitOfWork();
                var roles = await _personServices.Query();
                var first = roles.FirstOrDefault(x => x.EInfo_id == "1871");
                Console.WriteLine($"1 first time : the count of role is :{roles.Count} ${first?.EInfo_id}");


                Console.WriteLine($"insert a data into the table role now.");
                TimeSpan timeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                await _personServices.AddPersonAsync(new Person() {
                    Person_System_ID = "003AB1E106444CV",
                    EInfo_id = "1000",
                    Person_Type = "1",
                    SSN = "644-22-7981",
                    Name_Last = "Karimi",
                    Name_First = "Olubode",
                    Date_Birth = DateTime.Parse("3/23/2010"),
                });

                var roles2 = await _personServices.Query();
                Console.WriteLine($"2 second time : the count of role is :{roles2.Count}");


                //int ex = 0;
                //Console.WriteLine($"There's an exception!!");
                //Console.WriteLine($" ");
                //int throwEx = 1 / ex;

                //uow.Commit();
            }
            catch (Exception) {
                var roles3 = await _personServices.Query();
                Console.WriteLine($"3 third time : the count of role is :{roles3.Count}");
            }

            return "ok";
        }
        [HttpGet]
        [Authorize(Policy = "Policy_HSGDeMS")]
        public string Test2() => "123";


        [HttpGet]
        public async Task<object> Test3(string rid, string pid) {
            //return new MessageModel<>
            return await _essayFormServices.LoadEssayById(rid, pid);
        }
        [HttpPost]
        public async Task<object> Test4(RecPosApplicantEssayDto input) {
            //return new MessageModel<>
            return await _essayFormServices.SaveDB(input);
        }


        //private static readonly List<Product> Products = new();

        //[HttpPost]
        //public ActionResult Create([FromBody] Product product) {
        //    Products.Add(product);
        //    return Ok(Products);
        //}

        //[HttpPost]
        //public async Task<MessageModel<string>> Post([FromBody] Person request) {
        //    var data = new MessageModel<string>();

        //    var id = await _personServices.Add(request);
        //    data.success = id > 0;
        //    if (data.success) {
        //        data.data = id.ObjToString();
        //        data.msg = "添加成功";
        //    }

        //    return data;
        //}

        //[HttpPut]
        //public async Task<MessageModel<string>> Put([FromBody] Person request) {
        //    var data = new MessageModel<string>();
        //    data.success = await _personServices.Update(request);
        //    if (data.success) {
        //        data.msg = "更新成功";
        //        data.data = request?.Person_System_ID.ObjToString();
        //    }

        //    return data;
        //}

        //[HttpDelete]
        //public async Task<MessageModel<string>> Delete(int id)
        //{
        //    var data = new MessageModel<string>();
        //    var model = await _personServices.QueryById(id);
        //    //model.IsDeleted = true;
        //    data.success = await _personServices.Update(model);
        //    if (data.success)
        //    {
        //        data.msg = "删除成功";
        //        data.response = model?.Id.ObjToString();
        //    }

        //    return data;
        //}
    }
}